<?php

namespace App\Services;


use Intervention\Image\Facades\Image;
use Mrgoon\AliSms\AliSms;

/*
 * ImageResizeService Class
 * 将图片处理成3个不同尺寸的图
 */
class ImageResizeService {

    public $save_image_path='';

    public function resizeImage($image_path)
    {
        if ($this->save_image_path=='') {
            $path ="upimages";
            $storage_path = storage_path('app' . DIRECTORY_SEPARATOR . 'public' . DIRECTORY_SEPARATOR . $path . DIRECTORY_SEPARATOR . date("Ym") . DIRECTORY_SEPARATOR);
            $this->save_image_path = $storage_path;
        }
        //创建目录
        if (!file_exists($this->save_image_path)) {
            mkdir($this->save_image_path, 0777, true);
        }
        return $this->generateThumbnails($image_path);
    }

    private function generateThumbnails($image_path)
    {
        if (file_exists($image_path) && is_readable($image_path)) {
            $image = Image::make($image_path);
        } else {
            throw new \Exception("Image source not readable.");
        }
        //原图
        $originalPath =   pathinfo($image_path, PATHINFO_FILENAME) . '__o.jpg';
        $image->save($this->save_image_path.$originalPath);

        // 缩略图尺寸
        $thumbnailPath =  pathinfo($image_path, PATHINFO_FILENAME) . '__b.jpg';
        $this->saveThumbImage($image,1200,$thumbnailPath);
//
//        // 中等尺
        $size = 500;
        $thumbnailPath =  pathinfo($image_path, PATHINFO_FILENAME) . '__m.jpg';
        $this->saveThumbImage($image,$size,$thumbnailPath);

//        // 中等尺
        $size = 100;
        $thumbnailPath =  pathinfo($image_path, PATHINFO_FILENAME) . '__s.jpg';
        $this->saveThumbImage($image,$size,$thumbnailPath);

        $file_arr =  [
            'original-img' =>  $originalPath,
        ];

        return $file_arr;
    }

    private function saveThumbImage($image,$size,$thumbnailPath) {
        $image->resize($size, null, function ($constraint) {
            $constraint->aspectRatio();
        });

        $image->save($this->save_image_path.$thumbnailPath);
    }

}
